package yagwl.client.view.fnd;

import java.util.logging.Logger;

import yagwl.client.model.fnd.SessionCache;
import yagwl.client.model.fnd.SessionDto;
import yagwl.client.model.fnd.SessionRpcService;
import yagwl.client.model.fnd.SessionRpcServiceAsync;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

public abstract class AbstractEntryPoint implements EntryPoint {

  private static final Logger log = Logger.getLogger(AbstractEntryPoint.class
      .getName());
  private final SessionRpcServiceAsync sessionRpc = GWT
      .create(SessionRpcService.class);

  public void onModuleLoad() {
    log.info("onModuleLoad: Entering");
    // first get the session context ready
    sessionRpc.getSession(new AsyncCallback<SessionDto>() {
      @Override
      public void onFailure(Throwable caught) {
        Window.alert("onModuleLoad: " + caught.toString());
      }

      @Override
      public void onSuccess(SessionDto session) {
        SessionCache.getInstance().setSession(session);
        RootPanel.get("loading").setVisible(false);
        onModuleLoad2();
      }
    });

    History.addValueChangeHandler(new ValueChangeHandler<String>() {
      public void onValueChange(ValueChangeEvent<String> event) {
        String historyToken = event.getValue();
        log.info("ValueChangeHandler caught: " + historyToken);
        changeView(historyToken);
      }
    });

  }

  protected abstract void onModuleLoad2();

  protected abstract void changeView(String historyToken);

}
